package vmcs.customer;

import vmcs.common.VMCSException;
import vmcs.controller.TransactionController;
import vmcs.store.DrinksBrand;
import vmcs.store.DrinksStore;
import vmcs.store.DrinksStoreItem;
import vmcs.store.Store;
import vmcs.store.StoreController;
import vmcs.store.StoreItem;

public class DispenseController {

	private TransactionController transactionController;

	public DispenseController (TransactionController transactionController){
		this.transactionController = transactionController;
	}

	public void allowSelection(boolean allow) {

		if (allow){
			Store drinkStore = transactionController.getMainController().getStoreController().getStore(Store.DRINK);
			StoreItem[] storeItems = drinkStore.getItems();
			for (int i =0; i< storeItems.length; i++){
				StoreItem storeItem = storeItems[i];
				if (storeItem.getQuantity() == 0) {
					transactionController.getCustomerPanel().setDrinkSelectionBoxState(i, false);
					transactionController.getCustomerPanel().setDrinkSelectionBoxItemState(i, false);
				}
				else {
					transactionController.getCustomerPanel().setDrinkSelectionBoxState(i, true);
					transactionController.getCustomerPanel().setDrinkSelectionBoxState(i, true);
				}
			}
		} else {
			transactionController.getCustomerPanel().setDrinkSelectionBoxActive(allow);
		}
	}

	public void resetCan(){
		transactionController.getCustomerPanel().setCollectCanValue("No CAN");
	}

	public boolean dispenseDrink(int selectedBrand) throws VMCSException{
		boolean drinkDispensed = transactionController.getMainController().getMachineryController().dispenseDrink(selectedBrand);
	//	 transactionController.getCustomerPanel().getCollectCan().setValue(drinksBrand.getName());
		StoreItem storeItem = transactionController.getMainController().getStoreController().getStoreItem(Store.DRINK, selectedBrand);
		transactionController.getCustomerPanel().setCollectCanValue(storeItem.getContent().getName());
		if (drinkDispensed)
			updateDrinkSelection(selectedBrand);
		
     return true;
	}

	public void updateDrinkSelection(int selection){
		 DrinksStore drinksStore =(DrinksStore)transactionController.getMainController().getStoreController().getStore(Store.DRINK);
         DrinksStoreItem drinksStoreItem = null;
		try {
			drinksStoreItem = (DrinksStoreItem)drinksStore.getStoreItem(selection);
		} catch (VMCSException e) {
			e.printStackTrace();
		}
         DrinksBrand drinksBrand = (DrinksBrand)drinksStoreItem.getContent();
         int qty = drinksStoreItem.getQuantity();
         int price = drinksBrand.getPrice();
         String name = drinksBrand.getName();
         transactionController.getCustomerPanel().updateDrinkInput(selection, qty, price, name) ;
	}	

	public void updateDrinkPanel(){
		// TODO
	}	
}
